<?php
namespace Menory\Http\Client\Adapter;

use Menory\Http\Request;
use Menory\Http\Response;
use Menory\Http\Client\ClientError;

class CUrl {
    protected $connectTimeout = 30000;    // 30 second
    protected $readTimeout    = 80000;
    
    /**
     * @param Request $request
     * @return array
     */
    public function send($request) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($request->getRequestMethod()));
        $url = $request->getRequestUrl();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ("json" == $request->getDataType()) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData = json_encode($request->getParams()));
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Content-Length: ' . strlen($jsonData),
            ]);
        }
        else {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($request->getParams()));
        }
        if ($this->readTimeout) {
            curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
        }
        if ($this->connectTimeout) {
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
        }
        //https request
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
//        if (is_array($headers) && 0 < count($headers)) {
//            $httpHeaders = $this->getHttpHeaders($headers);
//            curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
//        }
        $response = new Response();
        $response->setBody(curl_exec($ch));
        $response->setStatus(curl_getinfo($ch, CURLINFO_HTTP_CODE));
        if (curl_errno($ch)) {
            return [null, new ClientError(curl_errno($ch), curl_error($ch))];
        }
        curl_close($ch);
        return [$response, null];
    }

}